<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/index.css">
    <script src="js/jquery-1.12.4.min.js"></script>
    <script src="js/template-native.js"></script>
    <script id="tem" type="text/html">
        <% for (var i = 0 ; i < comments.length ; i++) { %>
          <li>
            <p class="floor"><%= comments[i].id %>楼<a href="javascript:;" class="delete">删除</a></p>
            <p class="author">层主：<span class="name"><%= comments[i].username %></span></p>
            <p class="content"><%= comments[i].content %></p>
          </li>
      <% } %>
      </script>
</head>
<body>
    <div class="main">
        <div class="post">
            <h2>俗语接龙</h2>
            <p class="author">楼主：静静</p>
            <p class="txt">一日之计在于晨，一年之计在于春。</p>
        </div>
        <div class="reply">
            <h4>发表回复</h4>
            <p>用户名: <input type="text" class="user"></p>
            <textarea class="editor"></textarea>
            <input type="button" value="发表" class="btn">
        </div>
        <div class="cmts">
            <ul class="list">
                
            </ul>
        </div>
    </div>
    <script>
        var $list = $(".cmts .list");
        var $btn = $(".reply .btn");
        var $user = $(".reply .user");
        var $editor = $(".reply .editor");
        getData();
        function getData() {
          $.ajax({
            url: "http://localhost:3000/db",
            type: "GET",
            success: function (data) {
              $list.html(template("tem", data));
              $(".cmts .list .delete").click(function () {
                $li = $(this).parents("li");
                var index = $li.attr("uid");
                $.ajax({
                  url: "http://localhost:3000/comments/" + index,
                  type: "DELETE"            
                })
                $li.remove();
              })
            }
          });
        }
        $btn.click(function () {
          var username = $user.val();
          var content = $editor.val();
          $.ajax({
            url: "http://localhost:3000/comments",
            type: "POST",
            dataType: "json",
            data: {username: username, content: content},
            success: function (data) {
              getData();
            }
          })
        })

    </script>
</body>
</html>